#include <algorithm>
#include <cstdint>
#include <iostream>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
#include <fcntl.h>

#include "acl/acl.h"
#include "aclnn_col2_im_custom.h"

#define SUCCESS 0
#define FAILED 1

#define INFO_LOG(fmt, args...) fprintf(stdout, "[INFO]  " fmt "\n", ##args)
#define WARN_LOG(fmt, args...) fprintf(stdout, "[WARN]  " fmt "\n", ##args)
#define ERROR_LOG(fmt, args...) fprintf(stderr, "[ERROR]  " fmt "\n", ##args)

#define CHECK_RET(cond, return_expr) \
    do {                             \
        if (!(cond)) {               \
            return_expr;             \
        }                            \
    } while (0)

#define LOG_PRINT(message, ...)         \
    do {                                \
        printf(message, ##__VA_ARGS__); \
    } while (0)

bool ReadFile(const std::string &filePath, size_t fileSize, void *buffer, size_t bufferSize)
{
    struct stat sBuf;
    int fileStatus = stat(filePath.data(), &sBuf);
    if (fileStatus == -1) {
        ERROR_LOG("failed to get file %s", filePath.c_str());
        return false;
    }
    if (S_ISREG(sBuf.st_mode) == 0) {
        ERROR_LOG("%s is not a file, please enter a file", filePath.c_str());
        return false;
    }

    std::ifstream file;
    file.open(filePath, std::ios::binary);
    if (!file.is_open()) {
        ERROR_LOG("Open file failed. path = %s", filePath.c_str());
        return false;
    }

    std::filebuf *buf = file.rdbuf();
    size_t size = buf->pubseekoff(0, std::ios::end, std::ios::in);
    if (size == 0) {
        ERROR_LOG("file size is 0");
        file.close();
        return false;
    }
    if (size > bufferSize) {
        ERROR_LOG("file size is larger than buffer size");
        file.close();
        return false;
    }
    buf->pubseekpos(0, std::ios::in);
    buf->sgetn(static_cast<char *>(buffer), size);
    fileSize = size;
    file.close();
    return true;
}

bool WriteFile(const std::string &filePath, const void *buffer, size_t size)
{
    if (buffer == nullptr) {
        ERROR_LOG("Write file failed. buffer is nullptr");
        return false;
    }

    int fd = open(filePath.c_str(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWRITE);
    if (fd < 0) {
        ERROR_LOG("Open file failed. path = %s", filePath.c_str());
        return false;
    }

    auto writeSize = write(fd, buffer, size);
    (void) close(fd);
    if (writeSize != size) {
        ERROR_LOG("Write file Failed.");
        return false;
    }

    return true;
}

int64_t GetShapeSize(const std::vector<int64_t> &shape)
{
    int64_t shapeSize = 1;
    for (auto i : shape) {
        shapeSize *= i;
    }
    return shapeSize;
}

int Init(int32_t deviceId, aclrtStream *stream)
{
    // 固定写法，acl初始化
    auto ret = aclInit(nullptr);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclInit failed. ERROR: %d\n", ret); return FAILED);
    ret = aclrtSetDevice(deviceId);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSetDevice failed. ERROR: %d\n", ret); return FAILED);
    ret = aclrtCreateStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtCreateStream failed. ERROR: %d\n", ret); return FAILED);

    return SUCCESS;
}

template <typename T>
int CreateAclTensor(const std::vector<T> &hostData, const std::vector<int64_t> &shape, void **deviceAddr,
                    aclDataType dataType, aclTensor **tensor)
{
    auto size = GetShapeSize(shape) * sizeof(T);
    // 调用aclrtMalloc申请device侧内存
    auto ret = aclrtMalloc(deviceAddr, size, ACL_MEM_MALLOC_HUGE_FIRST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMalloc failed. ERROR: %d\n", ret); return FAILED);

    // 调用aclrtMemcpy将host侧数据拷贝到device侧内存上
    ret = aclrtMemcpy(*deviceAddr, size, hostData.data(), size, ACL_MEMCPY_HOST_TO_DEVICE);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtMemcpy failed. ERROR: %d\n", ret); return FAILED);

    // 调用aclCreateTensor接口创建aclTensor
    *tensor = aclCreateTensor(shape.data(), shape.size(), dataType, nullptr, 0, aclFormat::ACL_FORMAT_ND, shape.data(),
                              shape.size(), *deviceAddr);
    return SUCCESS;
}

int main(int argc, char **argv)
{
    INFO_LOG("=== Col2ImCustom Test Start ===");
    
    int32_t deviceId = 0;
    aclrtStream stream;
    auto ret = Init(deviceId, &stream);
    CHECK_RET(ret == 0, LOG_PRINT("Init acl failed. ERROR: %d\n", ret); return FAILED);

    // ========== Col2Im测试参数 ==========
    // 目标输出图像的形状
    int32_t N = 9;
    int32_t C = 10;
    int32_t H = 23;
    int32_t W = 1971;
    
    // 卷积参数
    int32_t kernel_h = 3;
    int32_t kernel_w = 2;
    int32_t stride_val = 5;
    int32_t padding_val = 4;
    int32_t dilation_val = 3;

    // 计算输入col的形状 [N, C*kH*kW, L]
    int32_t out_H = (H + 2 * padding_val - dilation_val * (kernel_h - 1) - 1) / stride_val + 1;
    int32_t out_W = (W + 2 * padding_val - dilation_val * (kernel_w - 1) - 1) / stride_val + 1;
    int32_t L = out_H * out_W;
    int32_t input_channels = C * kernel_h * kernel_w;

    INFO_LOG("Output image shape: [%d, %d, %d, %d]", N, C, H, W);
    INFO_LOG("Input col shape: [%d, %d, %d]", N, input_channels, L);
    INFO_LOG("Convolution params - kernel: (%d, %d), stride: %d, padding: %d, dilation: %d",
             kernel_h, kernel_w, stride_val, padding_val, dilation_val);

    // 输入：col格式 [N, C*kH*kW, L]
    std::vector<int64_t> inputColShape = {N, input_channels, L};
    // 输出：图像格式 [N, C, H, W]
    std::vector<int64_t> outputXShape = {N, C, H, W};
    
    size_t inputColShapeSize = GetShapeSize(inputColShape);
    size_t outputXShapeSize = GetShapeSize(outputXShape);

    INFO_LOG("Input col size: %zu elements", inputColShapeSize);
    INFO_LOG("Output image size: %zu elements", outputXShapeSize);

    // 检查文件
    std::string inputFile = "../input/input_col.bin";
    std::ifstream file(inputFile, std::ios::binary | std::ios::ate);
    if (!file.is_open()) {
        ERROR_LOG("Input file %s not found!", inputFile.c_str());
        return FAILED;
    }
    size_t fileSize = file.tellg();
    file.close();
    
    if (fileSize != inputColShapeSize * sizeof(float)) {
        ERROR_LOG("File size mismatch! Expected: %zu, Actual: %zu", 
                  inputColShapeSize * sizeof(float), fileSize);
        return FAILED;
    }
    INFO_LOG("Input file size OK: %zu bytes", fileSize);

    // 初始化数据
    std::vector<float> inputColHostData(inputColShapeSize);
    std::vector<float> outputXHostData(outputXShapeSize, 0);
    
    // 读取文件
    if (!ReadFile(inputFile, fileSize, inputColHostData.data(), inputColShapeSize * sizeof(float))) {
        ERROR_LOG("Read input file failed!");
        return FAILED;
    }
    INFO_LOG("Read input file success");

    // 创建tensors
    void *inputColDeviceAddr = nullptr;
    void *outputXDeviceAddr = nullptr;
    aclTensor *inputCol = nullptr;
    aclTensor *outputX = nullptr;
    
    INFO_LOG("Creating input tensor...");
    ret = CreateAclTensor(inputColHostData, inputColShape, &inputColDeviceAddr, aclDataType::ACL_FLOAT, &inputCol);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    
    INFO_LOG("Creating output tensor...");
    ret = CreateAclTensor(outputXHostData, outputXShape, &outputXDeviceAddr, aclDataType::ACL_FLOAT, &outputX);
    CHECK_RET(ret == ACL_SUCCESS, return FAILED);
    
    INFO_LOG("Tensors created successfully");

    // 调用算子
    uint64_t workspaceSize = 0;
    aclOpExecutor *executor;
    
    INFO_LOG("Calling aclnnCol2ImCustomGetWorkspaceSize...");
    ret = aclnnCol2ImCustomGetWorkspaceSize(inputCol, H, W, kernel_h, kernel_w, stride_val, padding_val, dilation_val, outputX, &workspaceSize, &executor);
    INFO_LOG("WorkspaceSize result: workspaceSize=%lu, executor=%p, ret=%d", 
             workspaceSize, executor, ret);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCol2ImCustomGetWorkspaceSize failed. ERROR: %d\n", ret); return FAILED);

    void *workspaceAddr = nullptr;
    if (workspaceSize > 0) {
        INFO_LOG("Allocating workspace: %lu bytes", workspaceSize);
        ret = aclrtMalloc(&workspaceAddr, workspaceSize, ACL_MEM_MALLOC_HUGE_FIRST);
        CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("allocate workspace failed. ERROR: %d\n", ret); return FAILED);
    }

    INFO_LOG("Calling aclnnCol2ImCustom...");
    ret = aclnnCol2ImCustom(workspaceAddr, workspaceSize, executor, stream);
    INFO_LOG("Col2ImCustom result: ret=%d", ret);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclnnCol2ImCustom failed. ERROR: %d\n", ret); return FAILED);

    // 4. （固定写法）同步等待任务执行结束
    ret = aclrtSynchronizeStream(stream);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("aclrtSynchronizeStream failed. ERROR: %d\n", ret); return FAILED);

    // 5. 获取输出的值，将device侧内存上的结果拷贝至host侧，需要根据具体API的接口定义修改
    auto size = GetShapeSize(outputXShape);
    std::vector<float> resultData(size, 0);
    ret = aclrtMemcpy(resultData.data(), resultData.size() * sizeof(resultData[0]), outputXDeviceAddr,
                      size * sizeof(float), ACL_MEMCPY_DEVICE_TO_HOST);
    CHECK_RET(ret == ACL_SUCCESS, LOG_PRINT("copy result from device to host failed. ERROR: %d\n", ret); return FAILED);
    void ** output1=(void **)(&resultData);
    //写出数据
    WriteFile("../output/output_x.bin", *output1, outputXShapeSize * sizeof(float));
    INFO_LOG("Write output success");

    // 6. 释放aclTensor，需要根据具体API的接口定义修改
    aclDestroyTensor(inputCol);
    aclDestroyTensor(outputX);

    // 7. 释放device资源，需要根据具体API的接口定义修改
    aclrtFree(inputColDeviceAddr);
    aclrtFree(outputXDeviceAddr);
    if (workspaceSize > 0) {
        aclrtFree(workspaceAddr);
    }
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return SUCCESS;
}
